package com.cci.kangdao.service.impl;

import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.CRMPlatformServiceDao;
import com.cci.kangdao.dao.WorkOrderRepairDao;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.NoticeService;
import com.cci.kangdao.task.AsyncTask;
import com.cci.kangdao.utilTool.CollectionUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.NumberUtils;
import com.cci.kangdao.utilTool.SmsUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 异步线程，执行程序中非必要同步执行的逻辑
 * @author: shiliqiang
 * @company: CTY Technology Co.,Ltd
 * @since: 2021/11/19 15:22
 * @version: V1.0
 */
@Service("asyncTaskServiceImpl")
public class AsyncTaskServiceImpl implements AsyncTask {

    protected static Logger log = LoggerFactory.getLogger(AsyncTaskServiceImpl.class);

    @Resource
    private WorkOrderRepairDao workOrderRepairDao;
    @Resource
    private NoticeService noticeService;

     /**
      * @description: 记录用户行为日志
      * @param:
      * @return: 
      * @exception:
      * @author: shiliqiang
      * @company: CTY Technology Co.,Ltd
      * @since: 2021/11/19 16:18
      * @version: V1.0
      */
    @Async
    public void userActionRecord (Map<String, Object> map) {
        workOrderRepairDao.saveOperation(map);
    }

     /**
      * @description: 保存工单负责人
      * @param:
      * @return:
      * @exception:
      * @author: shiliqiang
      * @company: CTY Technology Co.,Ltd
      * @since: 2021/11/19 16:26
      * @version: V1.0
      */
    @Async
    public void saveOrderPrincipal (Map<String, Object> map) {
        workOrderRepairDao.savePrincipal(map);
    }

    @Async
    public void newSendMsg (Map<String, Object> map, List<Map<String,Object>> sendList, int phoneMsg, int appMsg, Map<String,Object> otherMsg) {
        List<Map<String,Object>> sendMsgResultList = sendMsg(map,sendList,1,1,otherMsg);
        //将信息发送结果记录到数据库
        if(CollectionUtils.isNotEmpty(sendMsgResultList)){
            workOrderRepairDao.saveMsgOperation(sendMsgResultList);
        }
    }

    @Async
    public void asyncOrderStatusToCrm(String channalName, CRMPlatformServiceDao serviceDao, RedisClientUtils redisClientUtils, Map<String,Object> parameters){
        CRMResponeEntity CRMres;
        try {
            log.info("同步服务工单位置信息到crm 参数：" + parameters);
            CRMres = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(channalName,serviceDao,redisClientUtils,parameters,null);
            if(CRMres.getStatus()!=0) {
                //APP同步工单失败
                log.error("同步工单状态至CRM失败,状态："+CRMres.getStatus()+",错误信息："+CRMres.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            //APP同步工单失败
            log.error("同步工单状态至CRM失败："+e.getMessage(),e);
        }
    }

    /**
     * @param map      (ProcessorId,OrderId)
     * @param sendList 发送消息人列表(必须包含：ID,phone,clientId)
     * @param phoneMsg 是否发送短信（0：不发送，1：发送）
     * @param appMsg   是否APP发送（0：不发送，1：发送）
     * @param otherMsg (msgBody,msgTransMsg,msgTitle,function,category)
     */
    @Override
    public List<Map<String, Object>> sendMsg(Map<String, Object> map, List<Map<String, Object>> sendList, int phoneMsg, int appMsg, Map<String, Object> otherMsg) {
        //消息体
        String smsgbody = MapUtils.getString(otherMsg, "msgBody", "");
        String stransmsg = MapUtils.getString(otherMsg, "msgTransMsg", "");
        String smsgtitle = MapUtils.getString(otherMsg, "msgTitle", "");
        List<Map<String, Object>> sendResultList = new ArrayList<Map<String, Object>>();
        //当前操作人
        String ProcessorId = MapUtils.getString(map, "ProcessorId", "");
        //工单ID
        int OrderId = MapUtils.getIntValue(map, "OrderId");
        Set<String> phoneSet = sendList.stream().map(e -> {
            String phone = MapUtils.getString(e, "phone", "");
            return phone;
        }).filter(e -> {
            return StringUtils.isNotBlank(e);
        }).collect(Collectors.toSet());
        //去重
        sendList = sendList.stream().filter(e -> {
            String phone = MapUtils.getString(e, "phone", "");
            return phoneSet.contains(phone);
        }).collect(Collectors.toList());
        for (Map<String, Object> sendMap : sendList) {
            int ReceiverId = MapUtils.getIntValue(sendMap, "ID");
            if (phoneMsg == 1) {
                Map<String, Object> spmap = new HashMap<String, Object>();
                String phone = MapUtils.getString(sendMap, "phone", "");
                if (!"".equals(phone)) {
                    try {
                        SmsUtils.sendMessage(phone, smsgbody);//真正发送短信，暂时不放开，测试时放开
                        spmap = getSendMapMsg(OrderId, ReceiverId, smsgbody, 1, LocalTimeUtil.getRealCurrentTime(), 1, "", otherMsg, ProcessorId);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        String msg = e.getMessage().substring(0, 499);
                        spmap = getSendMapMsg(OrderId, ReceiverId, smsgbody, 1, LocalTimeUtil.getRealCurrentTime(), 0, msg, otherMsg, ProcessorId);
                    }
                } else {
                    //用户电话号码不存在
                    spmap = getSendMapMsg(OrderId, ReceiverId, smsgbody, 1, LocalTimeUtil.getRealCurrentTime(), 0, "用户电话号码不存在", otherMsg, ProcessorId);
                }
                sendResultList.add(spmap);
            }
            if (appMsg == 1) {
                Integer function = MapUtils.getInteger(otherMsg, "function");
                Integer category = MapUtils.getInteger(otherMsg, "category");
                Long processorId = NumberUtils.isNumber(ProcessorId) ? Long.valueOf(ProcessorId) : 0L;
                noticeService.push(function, category, Long.valueOf(OrderId), Long.valueOf(ReceiverId), null, smsgtitle, smsgbody, stransmsg, processorId);
            }
        }
        return sendResultList;
    }


    /**
     * 获取推送信息（当做信息推送记录）
     *
     * @param OrderId
     * @param ReceiverId
     * @param Content
     * @param SendType
     * @param SendTime
     * @param Status
     * @param ExceptionInfo
     * @return
     */
    public Map<String, Object> getSendMapMsg(int OrderId, int ReceiverId, String Content, int SendType, String SendTime, int Status, String ExceptionInfo, Map<String, Object> otherMsg, String ProcessorId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("OrderId", OrderId);
        String Function = MapUtils.getString(otherMsg, "function", "");
        String Category = MapUtils.getString(otherMsg, "category", "");
        map.put("Function", Function);
        map.put("Category", Category);
        map.put("ReceiverId", ReceiverId);
        map.put("Content", Content);
        map.put("SendType", SendType);
        map.put("SendTime", SendTime);
        map.put("Creator", ProcessorId);
        map.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
        map.put("IsRead", 0);
        map.put("Flag", 0);
        map.put("Status", Status);
        map.put("ExceptionInfo", ExceptionInfo);
        return map;
    }
}
